﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Warensoft.Unity.Communication.Client;
#if SERVER
namespace Warensoft.DataService.Models
#else
namespace Warensoft.Unity.Communication.Client.Models
#endif

{
    [Serializable]
    public class ResultInfo
    {
        public static ResultInfo Create(byte[] buffer)
        {
            buffer = buffer.Unzip();
            MemoryStream ms = new MemoryStream(buffer);
            BinaryReader br = new BinaryReader(ms);
            ResultInfo result = new ResultInfo();
            result.OperationDone = br.ReadBoolean();
            result.Message = br.ReadString();
            int objLength = br.ReadInt32();
            if (objLength != 0)
            {
                byte[] objBuffer = new byte[objLength];
                br.Read(objBuffer, 0, objLength);
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream ms1 = new MemoryStream(objBuffer);
                result.AdditionalData = bf.Deserialize(ms1);
                ms1.Close();
            }

            ms.Close();
            br.Close();
            buffer = null;
            return result;
        }
        /// <summary>
        /// 本次操作是否成功
        /// </summary>
        public bool OperationDone { get; set; }
        /// <summary>
        /// 如果不成功，该属性则返回错误信息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 本次操作的返回结果
        /// </summary>
        public object AdditionalData { get; set; }
        public ResultInfo()
        {
            this.Message = "";
        }
        public byte[] ToArray()
        {

            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            bw.Write(this.OperationDone);
            bw.Write(this.Message);
            if (this.AdditionalData == null)
            {
                bw.Write((int)0);
            }
            else
            {
                MemoryStream ms1 = new MemoryStream();
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms1, this.AdditionalData);
                var objBuffer = ms1.ToArray();
                ms1.Close();
                bw.Write(objBuffer.Length);
                bw.Write(objBuffer);
            }

            var buffer = ms.ToArray();
            ms.Close();
            bw.Close();
            //压缩
            buffer = buffer.Zip();

            return buffer;
        }
    }
}
